import axios from 'axios'
import Vue from 'vue'

axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => response, error => Promise.resolve(error.response))

function checkStatus (response) {
  if (response.status === 200 || response.status === 304) {
    return response
  }
  if (response.status >= 500) {
    return {
      data: {
        code: -500,
        status: false,
        message: response.statusText,
        data: response.statusText
      }
    }
  }
  return {
    data: {
      code: -404,
      status: false,
      message: response.statusText,
      data: response.statusText
    }
  }
}

function checkCode (res) {
  switch (res.status) {
    case 200:
      return res.data
    case -404:
      // console.error('404', res)
      break
    case -500:
      // console.error('500', res)
      break
    default:
      // console.error('err', res)
  }
  return false
}

export default {
  POST (url, data, errMsg) {
    const CancelToken = axios.CancelToken
    return axios.post(url, data, {
      timeout: 30000,
      headers: {
        'token': localStorage.getItem('token') || ''
    },
      cancelToken: new CancelToken(function executor (c) {
        if (Vue.$httpRequestList !== undefined) {
          Vue.$httpRequestList.push(c)
        }
      })
    }).then(checkStatus).then(res => checkCode(res, errMsg))
  },
  PUT (url, data, errMsg) {
    const CancelToken = axios.CancelToken
    return axios.put(url, data, {
      timeout: 30000,
      headers: {
        'token': localStorage.getItem('token') || ''
    },
      cancelToken: new CancelToken(function executor (c) {
        if (Vue.$httpRequestList !== undefined) {
          Vue.$httpRequestList.push(c)
        }
      })
    }).then(checkStatus).then(res => checkCode(res, errMsg))
  },
  GET (url, params, errMsg) {
    const CancelToken = axios.CancelToken
    return axios.get(url, {
      params: {
        _t: +(new Date()),
        ...params
      },
      timeout: 30000,
      headers: {
          'token': localStorage.getItem('token') || ''
      },
      cancelToken: new CancelToken(function executor (c) {
        if (Vue.$httpRequestList !== undefined) {
          Vue.$httpRequestList.push(c)
        }
      })
    }).then(checkStatus).then(res => checkCode(res, errMsg))
  }
}